#include "ImportExport.h"

#include "../Impp.h"
#include <wx/wfstream.h>
#include <wx/txtstrm.h>

namespace Impp
{

ImportExport::ImportExport()
{
}

ImportExport::~ImportExport()
{
}

void ImportExport::exportBuddyHistory(Buddy* buddy, const wxString & file){
	wxFileOutputStream fileOut(file);
	wxTextOutputStream out(fileOut);

	writeXmlStart(out);
	writeHistrory(out,buddy,wxDateTime((time_t)0));
	out << wxT("</log>\n");
}

void ImportExport::exportAllHistory(const wxString & file){
	wxFileOutputStream fileOut(file);
	wxTextOutputStream out(fileOut);

	writeXmlStart(out);

	std::vector<Buddy*> buddies = Impp::exemplar()->getAllBuddies();

	for (size_t i = 0; i < buddies.size(); ++i) {
		writeHistrory(out,buddies[i],wxDateTime((time_t)0));
	}
	out << wxT("</log>\n");
}

void ImportExport::writeXmlStart(wxTextOutputStream & out){
	out << wxT("<?xml version=\"1.0\" encoding=\"UTF-8\" ?>\n");
	out << wxT("<log>\n");
}

void ImportExport::writeHistrory(wxTextOutputStream & out, Buddy* buddy,const wxDateTime & since){

	Database* db = Impp::exemplar()->getDatabase();
	std::vector<HistoryEntry*> entries;
	db->getHistoryEntries(entries,Impp::exemplar()->getBuddy(buddy->getScreenName()), since);

	writeBuddyStart(out, buddy);

  	std::vector<HistoryEntry*>::iterator dIter(entries.begin());
  	for (; dIter != entries.end(); ++dIter) {
  		HistoryEntry* e = *dIter;
  		writeMessage(out,e->getTime(), e->getMsg(),e->isOutgoing());
  		delete e;
  	}

  	out << wxT("</buddy>\n");
}



void ImportExport::writeMessage(wxTextOutputStream & out, const wxDateTime & time, const wxString & message, bool outgoing){
	out << wxT("<message out=\"") << toBooleanString(outgoing);
	out << wxT("\" time=\"") << time.Format(wxT("%d-%m-%Y %H:%M:%S")) << wxT("\">");
	out << escapeString(message);
	out << wxT("</message>\n");
}

void ImportExport::writeBuddyStart(wxTextOutputStream & out, Buddy* buddy){
	out << wxT("<buddy screenname=\"") << escapeString(buddy->getScreenName()) << wxT("\">\n");
}

wxString ImportExport::toBooleanString(bool b){
	if(b){
		return wxT("true");
	}else{
		return wxT("false");
	}
}

wxString ImportExport::escapeString(wxString str){
	str.Replace(wxT("&"),wxT("&amp;"));
	str.Replace(wxT("<"),wxT("&lt;"));
	str.Replace(wxT(">"),wxT("&gt;"));
	str.Replace(wxT("\""),wxT("&quot;"));
	str.Replace(wxT("'"),wxT("&apos;"));
	return str;
}

}
